<template>
  <el-container>
    <el-header style="padding: 20px 20px 0 20px;height: initial">
      <el-form label-width="0" inline>
        <el-form-item label="">
          <el-input
            v-model="searchForm.userName"
            placeholder="账号(模糊匹配)"
          />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="searchForm.nickName"
            placeholder="昵称(模糊匹配)"
          />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="searchForm.email"
            placeholder="邮件(模糊匹配)"
          />
        </el-form-item>
        <el-form-item label="">
          <el-input
            v-model="searchForm.phone"
            placeholder="手机号(模糊匹配)"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option v-for="(item,index) in userStatus" :key="index" :label="item" :value="index" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button
            icon="el-icon-zoom-in"
            type="primary"
            plain
            @click="search"
          >查询</el-button>
          <el-button
            icon="el-icon-refresh"
            type="info"
            plain
            @click="reset"
          >清空</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            plain
            @click="add"
          >新增</el-button>

          <el-button
            icon="el-icon-close"
            type="danger"
            plain
            @click="deletes()"
          >批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main>
      <el-table
        v-loading.fullscreen.lock="loading"
        highlight-current-row
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="45"
          show-overflow-tooltip
        />
        <el-table-column
          v-for="item in tableColumn"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          show-overflow-tooltip
        >
          <div v-if="item.prop === 'imgUrl'" slot-scope="scope">
            <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.imgUrl"
              :preview-src-list="[scope.row.imgUrl]"
            />
          </div>
          <div v-else slot-scope="scope">{{ scope.row[item.prop] }}</div>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="460px">
          <template slot-scope="scope">
            <div class="settings">
              <el-button v-show="!scope.row.status" type="danger" size="mini" plain @click="changeStatus(scope.row)">封禁</el-button>
              <el-button v-show="scope.row.status" type="success" size="mini" plain @click="changeStatus(scope.row)">解除封禁</el-button>
              <el-tooltip content="初始密码：123456" placement="top">
                <el-button size="mini" type="warning" plain @click="initPassword(scope.row.id)">初始密码</el-button>
              </el-tooltip>
              <el-button
                type="warning"
                size="mini"
                plain
                @click="bindRole(scope.row)"
              >分配角色</el-button>
              <el-button
                type="warning"
                size="mini"
                plain
                @click="edit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="mini"
                plain
                @click="deletes([scope.row[deleteKey]])"
              >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <el-pagination
        background
        :current-page="pageNo"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalSize"
        @size-change="handleChangePageSize"
        @current-change="handleChangePageNo"
      />
    </el-footer>

    <el-dialog
      :title="dialogTitle"
      width="600px"
      :visible.sync="dialogValue"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form
        v-if="dialogValue"
        ref="ruleForm"
        style="margin-right: 20px"
        :model="ruleForm"
        :rules="rules"
        status-icon
        label-width="120px"
      >

        <el-form-item v-if="!ruleForm.id" label="用户名" prop="userName">
          <el-input v-model="ruleForm.userName" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="text" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="ruleForm.nickName" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" type="text" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.number="ruleForm.phone" type="text" />
        </el-form-item>
        <el-form-item label="头像" prop="imgUrl">
          <loon-upload ref="imgUrl" type="image/*" :folder="Base_API + '/icon/'" limit="1" :size="1024**2*2" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button
          type="primary"
          @click="save"
        >确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="授权-用户角色"
      :visible.sync="dialogValue2"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
    >
      <el-form v-if="dialogValue2" ref="grantForm" :model="grantForm" :rules="grantRules" label-width="120px" style="margin-right: 30px">
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="grantForm.roleId" placeholder="请选择" clearable>
            <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogValue2 = false">取 消</el-button>
        <el-button type="primary" @click="save2">确 定</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>
<style lang="less" scoped>
</style>
<script>
import { role_request, user_request as request } from '@/api/permission'
import curd from '@/mixins/curd'
import { mapGetters } from 'vuex'

export default {
  name: 'User',
  mixins: [curd],
  data() {
    return {
      request: request,
      searchForm: {
        userName: '',
        nickName: '',
        email: '',
        phone: '',
        status: ''
      },
      tableColumn: [
        {
          prop: 'userName',
          label: '账号'
        },
        {
          prop: 'nickName',
          label: '昵称'
        },
        {
          prop: 'imgUrl',
          label: '头像'
        },
        {
          prop: 'email',
          label: '邮件'
        },
        {
          prop: 'phone',
          label: '手机号'
        },
        {
          prop: 'statusText',
          label: '状态'
        }
      ],
      ruleForm: {
        id: undefined,
        userName: '',
        password: '',
        nickName: '',
        email: '',
        phone: '',
        imgUrl: ''
      },
      reseForm: {
        id: undefined,
        userName: '',
        nickName: '',
        password: '',
        email: '',
        phone: '',
        imgUrl: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 6, max: 11, message: '长度在 6 到 11 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 11, message: '长度在 6 到 11 个字符', trigger: 'blur' }
        ]
      },
      dialogValue2: false,
      grantForm: {},
      grantRules: {

      },
      roles: []
    }
  },
  computed: {
    ...mapGetters(['userStatus'])
  },
  created() {
    this.search()
  },
  methods: {
    formattTableData(tableData) {
      tableData.forEach(el => {
        el.statusText = this.userStatus[Number(el.status)]
      })
    },
    changeStatus(row) {
      this.request.changeStatus({
        id: row.id, status: row.status == 0 ? 1 : 0
      }).then(res => {
        this.play.message(this, res.status, res.errorMsg)
        this.getPage()
      }).catch(() => {
        row.status = row.status === 0 ? 1 : 0
      })
    },
    initPassword(id) {
      var _self = this
      this.request.initPassword(id).then((data) => {
        _self.play.message(_self, data.status, '初始化' + data.errorMsg)
      }).catch((error) => {
        console.info(error)
      })
    },
    add() {
      this.ruleForm = { ...this.reseForm }
      this.dialogValue = true
    },
    edit(row) {
      console.log(row, this.ruleForm)
      for (const key in this.ruleForm) {
        this.ruleForm[key] = row[key]
      }
      this.ruleForm.id = row.id
      this.dialogValue = true
      this.$nextTick(() => {
        this.$refs['imgUrl'].reset(row.imgUrl ? [{ url: row.imgUrl }] : [])
      })
    },
    async save() {
      if (!this.$refs['imgUrl'].isNull()) {
        const imgUrl = await this.$refs['imgUrl'].uploadFile()
        this.ruleForm.imgUrl = imgUrl[0]
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const methodName = this.ruleForm.id ? 'edit' : 'add'
          const form = methodName === 'add' ? { ...this.ruleForm } : { ...this.ruleForm, userName: undefined, password: undefined }
          this.request[methodName]({ ...form })
            .then((data) => {
              this.play.message(this, data.status, data.errorMsg)
              this.search()
              this.dialogValue = false
            })
            .catch((error) => {
              console.info(error)
            })
        }
      })
    },
    // 分配角色
    bindRole(row) {
      this.grantForm = {
        id: row.id,
        roleId: ''
      }
      this.dialogValue2 = true
      // 先获取角色列表所有
      role_request.list().then((res) => {
        this.roles = res.list
        // 获取当用前用户绑定的角色
        this.request.getRoleBindMenu(row.id).then(res2 => {
          this.grantForm.roleId = res2.data.roleId
        })
      }).catch((error) => {
        console.info(error)
      })
    },
    save2() {
      this.$refs.grantForm.validate((valid) => {
        if (valid) {
          this.request.userBindRole({ ...this.grantForm, roleId: this.grantForm.roleId ? this.grantForm.roleId : 0 }).then((data) => {
            this.play.message(this, data.status, data.errorMsg)
            this.dialogValue2 = false
          }).catch((error) => {
            console.info(error)
          })
        }
      })
    }
  }
}
</script>
